package com.acc.accrpc.loadbalancer;

import com.acc.accrpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 随机负载均衡器
 */
public class RandomLoadBalancer implements LoadBalancer {

    private final Random random = new Random();

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        int size = serviceMetaInfoList.size();
        if (size == 0) {
            return null;
        }
        // 只有 1 个服务，不用随机
        if (size == 1) {
            return serviceMetaInfoList.get(0);
        }

        // 计算所有服务的总性能分数
        int totalWeight = 0;
        for (ServiceMetaInfo service : serviceMetaInfoList) {
            totalWeight += service.getPerformanceScore();
        }

        // 如果总权重无效，使用均匀随机选择
        if (totalWeight <= 0) {
            return serviceMetaInfoList.get(random.nextInt(size));
        }

        // 生成一个在 [0, totalWeight) 区间的随机数
        int randomNumber = random.nextInt(totalWeight);
        int currentWeight = 0;
        for (ServiceMetaInfo service : serviceMetaInfoList) {
            currentWeight += service.getPerformanceScore();
            if (randomNumber < currentWeight) {
                return service;
            }
        }

        // 理论上不会到达这里，若发生则回退到均匀随机
        return serviceMetaInfoList.get(random.nextInt(size));
    }
}
